package cn.net.sinodata.common.hazelcast.config;

import cn.net.sinodata.common.core.constant.Constants;
import cn.net.sinodata.common.core.utils.SpringUtils;
import com.hazelcast.config.Config;
import com.hazelcast.config.XmlConfigBuilder;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 基于 Hazelcast 分布式缓存配置类
 *
 * @author yinliangyun
 */
@Slf4j
@Configuration
public class CacheConfig {

    @Bean
    public HazelcastInstance hazelcastInstance() {
        log.info("CacheConfig hazelcastInstance start");
        HazelcastInstance hazelcastInstance = null;
        Config config = null;
        try {
            config = new XmlConfigBuilder(CacheConfig.class.getClassLoader().getResourceAsStream(getXmlName())).build();
            if (null != config) {
                log.info("CacheConfig hazelcastInstance config toString : {}", config.toString());
            }
            hazelcastInstance = Hazelcast.newHazelcastInstance(config);
        } catch (Exception e) {
            log.error("CacheConfig hazelcastInstance Exception" + "_" + e.getMessage(), e);
        }
        log.info("CacheConfig hazelcastInstance end");
        return hazelcastInstance;
    }

    /**
     * Description: 获取系统当前环境使用的配置文件名称
     *
     * @return
     */
    private static String getXmlName() {
        String xmlName = "";
        String springActiveProfile = SpringUtils.getActiveProfile();
        log.info("CacheConfig getXmlName springActiveProfile : {}", springActiveProfile);
        if (Constants.SPRING_ACTIVE_PROFILE_DEV.equals(springActiveProfile)) {
            xmlName = Constants.HAZELCAST_DEV_XML;
        } else if (Constants.SPRING_ACTIVE_PROFILE_SIT.equals(springActiveProfile)) {
            xmlName = Constants.HAZELCAST_SIT_XML;
        } else if (Constants.SPRING_ACTIVE_PROFILE_UAT.equals(springActiveProfile)) {
            xmlName = Constants.HAZELCAST_UAT_XML;
        } else if (Constants.SPRING_ACTIVE_PROFILE_PP.equals(springActiveProfile)) {
            xmlName = Constants.HAZELCAST_PP_XML;
        } else if (Constants.SPRING_ACTIVE_PROFILE_PI.equals(springActiveProfile)) {
            xmlName = Constants.HAZELCAST_PI_XML;
        } else if (Constants.SPRING_ACTIVE_PROFILE_PRO.equals(springActiveProfile)) {
            xmlName = Constants.HAZELCAST_PRO_XML;
        } else {
            log.info("CacheConfig getXmlName fail");
        }
        return xmlName;
    }

}
